import 'dart:io';
import 'dart:typed_data';
import 'package:csv/csv.dart';
import '../utils/encoding_util.dart';

/// 命令行测试程序，用于验证CSV文件的编码处理
void main() async {
  // 测试文件路径，可以根据需要修改
  final String filePath = 'test_words_final.csv';
  
  print('测试CSV文件编码: $filePath');
  
  try {
    final file = File(filePath);
    if (!await file.exists()) {
      print('错误: 文件不存在: $filePath');
      return;
    }
    
    print('文件存在，开始读取...');
    
    // 读取文件字节
    final Uint8List bytes = await file.readAsBytes();
    print('文件大小: ${bytes.length} 字节');
    
    // 检查BOM标记
    final bool hasBom = bytes.length >= 3 && 
        bytes[0] == 0xEF && 
        bytes[1] == 0xBB && 
        bytes[2] == 0xBF;
    print('包含BOM标记: ${hasBom ? "是" : "否"}');
    
    // 去除BOM标记
    final Uint8List processedBytes = EncodingUtil.removeBomFromBytes(bytes);
    print('处理后字节数: ${processedBytes.length}');
    
    // 尝试UTF-8解码
    print('\n=== 尝试UTF-8解码 ===');
    try {
      final String content = utf8.decode(processedBytes);
      print('UTF-8解码成功，前100个字符:');
      print(content.substring(0, content.length > 100 ? 100 : content.length));
      
      // 解析CSV
      final List<List<dynamic>> csvTable = const CsvToListConverter().convert(content);
      print('CSV解析成功，共 ${csvTable.length} 行');
      
      if (csvTable.isNotEmpty) {
        print('表头: ${csvTable[0].join(", ")}');
        if (csvTable.length > 1) {
          print('第一行数据: ${csvTable[1].join(", ")}');
        }
      }
    } catch (e) {
      print('UTF-8解码失败: $e');
    }
    
    // 尝试Latin1解码
    print('\n=== 尝试Latin1解码 ===');
    try {
      final String content = latin1.decode(processedBytes);
      print('Latin1解码成功，前100个字符:');
      print(content.substring(0, content.length > 100 ? 100 : content.length));
      
      // 解析CSV
      final List<List<dynamic>> csvTable = const CsvToListConverter().convert(content);
      print('CSV解析成功，共 ${csvTable.length} 行');
      
      if (csvTable.isNotEmpty) {
        print('表头: ${csvTable[0].join(", ")}');
        if (csvTable.length > 1) {
          print('第一行数据: ${csvTable[1].join(", ")}');
        }
      }
    } catch (e) {
      print('Latin1解码失败: $e');
    }
    
    // 尝试String.fromCharCodes解码
    print('\n=== 尝试String.fromCharCodes解码 ===');
    try {
      final String content = String.fromCharCodes(processedBytes);
      print('String.fromCharCodes解码成功，前100个字符:');
      print(content.substring(0, content.length > 100 ? 100 : content.length));
      
      // 解析CSV
      final List<List<dynamic>> csvTable = const CsvToListConverter().convert(content);
      print('CSV解析成功，共 ${csvTable.length} 行');
      
      if (csvTable.isNotEmpty) {
        print('表头: ${csvTable[0].join(", ")}');
        if (csvTable.length > 1) {
          print('第一行数据: ${csvTable[1].join(", ")}');
        }
      }
    } catch (e) {
      print('String.fromCharCodes解码失败: $e');
    }
    
    print('\n测试完成');
  } catch (e) {
    print('测试出错: $e');
  }
}